﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Xml;
using System.Globalization;
using Microsoft.SharePoint.Utilities;

namespace SharePointOfView.ExtensionMethods
{
    public static class FeatureReceiverProperties
    {
        /// <summary>
        /// Deletes the uploaded files. (Inspired from a Robert L. Bogue’s code | http://www.thorprojects.com/blog)
        /// </summary>
        /// <param name="properties">The properties.</param>
        public static void SovDeleteUploadedFiles(this SPFeatureReceiverProperties properties)
        {
            SPWeb web = null;
            switch (properties.Definition.Scope)
            {
                case SPFeatureScope.Site:
                    SPSite site = (SPSite)properties.Feature.Parent;
                    web = site.RootWeb;
                    break;
                case SPFeatureScope.Web:
                    web = (SPWeb)properties.Feature.Parent;
                    break;
                default:
                    return;
            }

            foreach (SPElementDefinition element in properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture))
            {
                if (element.ElementType == "Module")
                {
                    string fileUrl = string.Empty;

                    XmlNode moduleNode = element.XmlDefinition;
                    if (moduleNode.Attributes["Url"] != null)
                        fileUrl = moduleNode.Attributes["Url"].Value + '/';

                    XmlNodeList fileNodes = moduleNode.SelectNodes("*[local-name()='File']");

                    if (fileNodes != null)
                    {
                        foreach (XmlNode fileNode in fileNodes)
                        {
                            string fullFileUrl = SPUrlUtility.CombineUrl(fileUrl, fileNode.Attributes["Url"].Value);
                            SPFile file = web.GetFile(fullFileUrl);

                            if (file != null && file.Exists)
                                file.Delete();
                        }
                    }
                }
            }
        }
    }
}
